using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

using SPath = System.IO.Path;

namespace Gazebo.Core
{
    public class PreferencesManager
    {
        public static PreferencesManager GlobalManager { get; private set; }
        
        static PreferencesManager()
        {
            string dir = SPath.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Gazebo");
            
            Directory.CreateDirectory(dir);
            
            string path = SPath.Combine(dir, "config.xml");
            
            GlobalManager = new PreferencesManager(path);
        }
        
        public string Path { get; private set; }
        
        private XDocument preferencesDocument;
        
        public object WriteLock { get; private set; }
        
        public PreferencesManager(string path)
        {
            WriteLock = new object();
            
            preferencesDocument = new XDocument();
            
            Path = path;
            Load();
        }
        
        private void Clear()
        {
            lock (WriteLock) {
                preferencesDocument = new XDocument(new XElement("GazeboPreferences"));
            }
        }
        
        private void Load()
        {
            if (!File.Exists(Path)) {
                Clear();
                return;
            }
            
            lock (WriteLock) {
	            preferencesDocument = XDocument.Load(Path);
            }
        }
        
        public void Save()
        {
            lock (WriteLock) {
            	preferencesDocument.Save(Path);
            }
        }
        
        public XElement GetAddinPreferences(string addin)
        {
            lock (WriteLock) {
                XElement e = (from i in preferencesDocument.Root.Elements("Addin")
                    where (string) i.Attribute("name") == addin select i).FirstOrDefault();
                
                if (e != null) {
                    return e;
                }
                
                e = new XElement("Addin", new XAttribute("name", addin));
                
                preferencesDocument.Root.Add(e);
                
                return e;
            }
        }
    }
}
